<?php


namespace App\Services;


use App\Exceptions\ApiException;
use App\Models\Admin;
use App\Models\AuthGroup;
use App\Models\AuthGroupAccess;

class AuthGroupAccessService
{
    /**
     * 授权权限组
     */
    public function add($data){
        $adminId=$data['admin_id'];
        $groupIds=$data['group_ids'];
        //判断管理员是否存在
        $admin=Admin::find($adminId);
        if (empty($admin)){
            throw new ApiException(20004);
        }

        //判断分组是否存在
        $groupArr = array_unique(explode(',',$groupIds));
        $authGroup = AuthGroup::whereIn('id',$groupArr)->pluck('id')->toArray();
        $diff = array_diff($groupArr,$authGroup);
        if (!empty($diff)){
            throw new ApiException(20005);
        }

        //判断当前管理员的权限组是否存在:存在则更新，不存在则插入
        $groupAccess = AuthGroupAccess::firstOrNew(['admin_id'=>$adminId]);
        $groupAccess->admin_id = $adminId;
        $groupAccess->group_ids = $groupIds;
        $groupAccess->save();
    }

}
